﻿$(document).ready(function () {
    $('body').keypress(function (e) {
        if (e.keyCode == 13) {
            doCheck();
            e.preventDefault();
        }
    });

    $('.button').hover(
    function () {
        $(this).css('background', '#000').css('color', '#fff');
    },
    function () {
        $(this).css('background', '#ddd').css('color', '#000');
    });

    $('#ajax .button').click(function () {
        doCheck();
    });
});

function doCheck() {
    var fname = $.trim($('#txtName').val().split(' ')[0]);
    var lname = $.trim($('#txtName').val().split(' ')[1]);

    $.ajax({
        type: 'POST',
        url: 'AJAX.aspx/CheckClientName',
        data: '{"fname":"' + fname + '", "lname":"' + lname + '"}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            //Parse the JSON result and process
            var obj = $.parseJSON(msg.d)
            showResult(obj);
        },
        error: function (xml, textStatus, errorThrown) {
            alert(xml.status + "||" + xml.responseText);
        }
    });
}

function showResult(obj) {
    $('#txtName').focus().select();
    if (obj !== null) {
        $('#msg').html('<b>' + $('#txtName').val() + '</b> is NOT available!').css('color', '#ff0000');
        $('#found').html('<b>Found:</b> ' + obj.FirstName + ' ' + obj.LastName + ' - ID: ' + obj.Id);
    }
    else {
        $('#msg').html('<b>' + $('#txtName').val() + '</b> is available.').css('color', '#00ff00');
        $('#found').html('');
    }
}